import { usePermissionStore } from '@/store/permiss';
import { cloneDeep } from 'lodash-es';
import { RouteRecordRaw } from 'vue-router';
import { AppRouteRecordRaw } from '../types';
import * as Application from './app';
import * as Basic from './basic';

let BASIC_ROUTES: AppRouteRecordRaw[] = []
let applicationRoutes: AppRouteRecordRaw[] = []

const basic: any = Basic
const application: any = Application
let key: string

for ( key in basic) {
  const MODULE = basic[key] as AppRouteRecordRaw
  BASIC_ROUTES.push(MODULE)
}


for (key in application) {
  const MODULE = application[key] as AppRouteRecordRaw
  applicationRoutes.push(MODULE) 
}


// const basicRoutes = [PARENT_LAYOUT_ROUTE,SYSTEM_ROUTE, REDIRECT_ROUTE, ERROR_LOG_ROUTE,PAGE_NOT_FOUND_ROUTE]
const basicRoutes = BASIC_ROUTES.sort((a,b) => {
  if (typeof a.meta.sort === 'number' && typeof b.meta.sort === 'number') {

    return a?.meta.sort - b?.meta?.sort

  } else {
    return 0
  }
})
// const asyncRoutes = ASYNC_ROUTE

// 在一级路由挂载二级路由
const handleDynamicAddRoute = () => {
  basicRoutes.forEach(basicRoute=> {
    applicationRoutes.forEach(appRoute => {
      if (appRoute.parent && appRoute.parent === basicRoute.name) {
        if (basicRoute.children) {
          basicRoute.children?.push(appRoute)
        } else {
          basicRoute.children = []
          basicRoute.children.push(appRoute)
        }
      }
    })
  });
}

handleDynamicAddRoute()



export const allRoutes:RouteRecordRaw[]|any = [
  ...basicRoutes,
]




// Sidebar组件menu
// 删除所有component防止sidebar重复引用
export const getAllRoutes  =  cloneDeep(allRoutes).map((e:AppRouteRecordRaw)=> {
  if (e.component) {
    e.component = undefined
  }
  return e
})

const handlerMenuConfig = (routes: AppRouteRecordRaw[]): AppRouteRecordRaw[] => {
  const permissStore = usePermissionStore()
  const userRole = permissStore.userRole
  let validRoutes: AppRouteRecordRaw[] = []
  if (userRole.includes('administrator')) {
    return routes
  } else {
    validRoutes = routes.filter(e => {
      const routePermiss = e.meta.permission || ""
      return permissStore.userPermissions.includes(routePermiss)
    })
    return validRoutes
  }
}

